package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.LogicException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.util.List;
import java.util.UUID;

import static cn.wolfcode.wolf2w.util.Consts.VERIFY_CODE_VAI_TIME;

@Service
public class UserInfoServiceImpl implements IUserInfoService{


    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private IRedisService redisService;
    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        userInfoRepository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        userInfoRepository.deleteById(id);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public UserInfo get(String id) {
        UserInfo userInfo = userInfoRepository.findById(id).orElse(null);
        return userInfo;
    }

    @Override
    public List<UserInfo> list() {

        return userInfoRepository.findAll();
    }

    @Override
    public Boolean checkPhone(String phone) {
        UserInfo userInfo= userInfoRepository.findByPhone(phone);
        return userInfo != null;
    }

    @Override
    public void sendVerifyCode(String phone, String url, String appkey) {
        //生成随机验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        StringBuilder sb = new StringBuilder(80);
        sb.append("您的验证码为:").append(code).append(",请在").append(VERIFY_CODE_VAI_TIME).append("分钟之内输入");
        //短信频率控制
        //判断是否在有效期内
        Boolean hasKey = redisService.hasKey(phone);
        if(!hasKey){
            //有效期外重新创建
            redisService.setTime(phone);
            System.out.println(sb);
        } else{
            //获取次数
            Integer time = redisService.getTime(phone);
            if(time > 1){
                redisService.decrTime(phone);
                System.out.println(sb);
            }else{
                throw new LogicException("短信发送太过频繁");
            }

        }




        //真实发短信
       /* RestTemplate restTemplate = new RestTemplate();
        //参数一:发送路径;参数二:返回类型;参数三四五都是配置文件中需要带进去的值,第一个为手机号,第二个为内容第三个为appkey值
        String str = restTemplate.getForObject(url, String.class, phone, "【叩丁狼】" + sb.toString(), appkey);
        System.out.println(str);
        if(!str.contains("Success")){
            throw new LogicException("短信发送失败");
        }*/
        //将phone 和 code 存到redis中
        redisService.sendVerifyCode(phone,code);
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //做参数验证
        //判断参数是否为空
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断手机号码是否符合格式
        AssertUtil.testPhone(phone,"手机号码格式错误");
        //判断手机号是否已注册
        Boolean aBoolean = this.checkPhone(phone);
        if(aBoolean){
            throw new LogicException("手机号已被注册");
        }
        //判断2次密码是否一致
        AssertUtil.isEuqal(password,rpassword,"输入的密码不一致");
        //判断验证码是否正确
        String code = redisService.getVerifyCode(phone);
        if(code==null || !verifyCode.equalsIgnoreCase(code)){
            throw new LogicException("验证码失效或错误");
        }
        //如果以上都没问题则执行保存操作
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password);
        userInfo.setGender(UserInfo.GENDER_SECRET);
        userInfo.setLevel(0);
        userInfo.setCity("");
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setInfo("");
        userInfo.setState(UserInfo.STATE_NORMAL);

        //throw new RuntimeException("一个乱七八糟的bug");
        userInfoRepository.save(userInfo);
    }



    @Override
    public UserInfo login(String username, String password) {
        //判断用户名和密码是否为空
        AssertUtil.hasLength(username,"用户名不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        //检查是否有该用户
        UserInfo user = userInfoRepository.findByPhone(username);
        if(user == null){
            throw new LogicException("账号不存在");
        }
        return user;
    }

    @Override
    public List<UserInfo> queryByCity(String keyword) {
        List<UserInfo> userInfoList = userInfoRepository.findByCity(keyword);
        return userInfoList;
    }

}
